package design_pattern.TwoPhaseTermination;

import java.util.Random;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/18 13:55
 * @Version 1.0
 */
public class CounterIncreasment extends Thread {
    private volatile boolean terminated = false;
    private int counter = 0;
    private Random random = new Random(System.currentTimeMillis());

    @Override
    public void run() {
        try {
            while (!terminated){
                System.out.println(Thread.currentThread().getName()+ " " +counter++);
                Thread.sleep(random.nextInt(1000));
            }
        } catch (InterruptedException e) {
            //e.printStackTrace();
        } finally {
            clean();
        }
    }

    private void clean() {
        System.out.println("do some clean work for the second phase current counter:"+counter);
    }

    public void close(){
        this.terminated = true;
        this.interrupt();
    }
}
